package com.wxl.sharding.db;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.google.common.collect.Range;
import com.wxl.util.SnowflakeIdWorker;
import lombok.Generated;
import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.infra.datanode.DataNodeInfo;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 标准分片策略：单分片键时的精确查询或范围查询
 * 对应StandardShardingStrategy。提供对SQL语句中的=, IN和BETWEEN AND的分片操作支持。
 * StandardShardingStrategy只支持单分片键，
 * 提供PreciseShardingAlgorithm和RangeShardingAlgorithm两个分片算法。
 * PreciseShardingAlgorithm是必选的，用于处理=和IN的分片。
 * RangeShardingAlgorithm是可选的，用于处理BETWEEN AND分片，如果不配置RangeShardingAlgorithm，
 * SQL中的BETWEEN AND将按照全库路由处理。
 *
 * 这里定义完成后并不会直接生效  需要使用spi 在resources/services/*中添加该类
 *
 */
public class MyDbShardingAlgo implements StandardShardingAlgorithm<Long> {

    private Properties props = new Properties();

    // 分库名前缀（格式：order_yyyyMM）
    private String dbPrefix = "order_db_";


    @Override
    public String doSharding(Collection<String> availableTargetNames,
                             PreciseShardingValue<Long> preciseShardingValue) {
        Long orderId = preciseShardingValue.getValue();

        // 1. 格式化为年月字符串
        String month = SnowflakeIdWorker.getYYYYMM(orderId);

        // 2. 构造分库名称
        String targetDB = dbPrefix + month;

        // 3. 验证分库是否存在
        if (availableTargetNames.contains(targetDB)) {
            System.out.println("找到数据库："+targetDB);
            return targetDB;
        }

        throw new IllegalArgumentException("无效的分库: " + targetDB + " 可用分库: " + availableTargetNames);
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Long> rangeShardingValue) {

        String columnName = rangeShardingValue.getColumnName();
        DataNodeInfo dataNodeInfo = rangeShardingValue.getDataNodeInfo();
        String logicTableName = rangeShardingValue.getLogicTableName();
        Range<Long> valueRange = rangeShardingValue.getValueRange();
        Long aLong = valueRange.upperEndpoint();
        Long aLong1 = valueRange.lowerEndpoint();


        return collection;
    }



    @Override
    public String getType() {
        //对应yml中的type,这里怎么定义，那里就怎么写
        return "MY_DB_MONTH";
    }



    @Generated
    public Properties getProps() {
        return this.props;
    }


    @Override
    public void init(Properties properties) {
        this.props = properties;
    }
}